page.tsx
1import { notFound } from 'next/navigation'
2import { BlogPost } from '@/components/blog-post'
3import { BlogList } from '@/components/blog-list'
4import { generateMeta } from '@/lib/generateMeta'
5import { getContent, sortContentByDate } from '@/lib/content'
6import { headers } from 'next/headers'
7
8interface Props {
9 params: {
10 slug: string[]
11 }
12}
13
14export function generateMetadata({ params }: Props) {
15 const { slug } = params
16
17 if (slug.length === 3) {
18 const [year, month, day] = slug
19 return generateMeta({
20 title: `Blog Posts from ${month}/${day}/${year}`,
21 path: `/blog/${year}/${month}/${day}`,
22 })
23 } else if (slug.length === 2) {
24 const [year, month] = slug
25 return generateMeta({
26 title: `Blog Posts from ${month}/${year}`,
27 path: `/blog/${year}/${month}`,
28 })
29 } else if (slug.length === 1) {
30 const [year] = slug
31 return generateMeta({
32 title: `Blog Posts from ${year}`,
33 path: `/blog/${year}`,
34 })
35 }
36
37 return generateMeta({
38 title: 'Blog',
39 path: '/blog',
40 })
41}
42
43export default function BlogPage({ params }: Props) {
44 const { slug } = params
45 const allPosts = sortContentByDate(getContent('blog'))
46 const locale = headers().get('accept-language')?.split(',')[0] || 'en-US'
47
48 // Check if there is no first slug
49 if (slug.length === 0) {
50 return <BlogList posts={allPosts} locale={locale} />
51 }
52
53 try {
54 if (slug.length === 4) {
55 // Single post page
56 const [year, month, day, postSlug] = slug
57 const post = allPosts.find((post) => {
58 const date = new Date(post.metadata.date)
59 return (
60 date.getFullYear() === parseInt(year) &&
61 date.getMonth() + 1 === parseInt(month) &&
62 date.getDate() === parseInt(day) &&
63 post.slug === postSlug
64 )
65 })
66
67 if (!post) return notFound()
68 return <BlogPost post={post} locale={locale} allPosts={allPosts} />
69 }
70
71 // Filter posts by date components
72 const filteredPosts = allPosts.filter((post) => {
73 const date = new Date(post.metadata.date)
74 const [year, month, day] = slug
75
76 if (slug.length === 3) {
77 return (
78 date.getFullYear() === parseInt(year) &&
79 date.getMonth() + 1 === parseInt(month) &&
80 date.getDate() === parseInt(day)
81 )
82 } else if (slug.length === 2) {
83 return (
84 date.getFullYear() === parseInt(year) &&
85 date.getMonth() + 1 === parseInt(month)
86 )
87 } else if (slug.length === 1) {
88 return date.getFullYear() === parseInt(year)
89 }
90
91 return true
92 })
93
94 return <BlogList posts={filteredPosts} locale={locale} />
95 } catch (error) {
96 console.error('Error:', error)
97 return notFound()
98 }
99}
100